package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.beans.UserActiveBean;
import com.atguigu.edu.realtime.beans.UserLoginBean;
import com.atguigu.edu.realtime.utils.DateFormatUtil;
import com.atguigu.edu.realtime.utils.MyClickhouseUtil;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

import org.apache.flink.util.Collector;

import java.time.Duration;

public class DwsUserActiveWindow {
    public static void main(String[] args) throws Exception {
        //TODO 1.基本环境准备
        //1.1 指定流处理环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //1.2 设置并行度
        env.setParallelism(4);
        //TODO 2.检查点相关的设置
/*env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        // 2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        // 2.3 job取消后，检查点是否保存
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        // 2.4 两个检查点之间的最小时间间隔
        // 0秒时开始备份检查点，但数据很多到了第6秒才完成，那第5秒的时候还要备份检查点吗？不要，第8秒后再开始
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        // 2.5 设置重启策略
        // 一共3次
        //env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3, 3000L));
        // 每30天有3次
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));
        // 2.6 设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        // 状态是存在TaskManager堆内存中的，检查点存在什么地方？有可能在内存里面，也有可能在文件系统里，我们设置一下
        // 存在JobManager中
        //env.getCheckpointConfig().setCheckpointStorage(new JobManagerCheckpointStorage());
        // 存在文件系统中
        env.getCheckpointConfig().setCheckpointStorage("hdfs://8.130.41.215:8020/edu/ck");
        // 2.7 指定操作Hadoop的用户
        System.setProperty("HADOOP_USER_NAME", "atguigu");*/
        //TODO 3.从kafka的page_log主题中读取数据
        String topic = "dwd_traffic_page_log";
        String groupId = "dws_user_active_group";
        //3.2 创建消费者对象
        FlinkKafkaConsumer<String> kafkaConsumer = MyKafkaUtil.getKafkaConsumer(topic, groupId);
        //3.3 消费数据 封装为流
        DataStreamSource<String> kafkaStrDS = env.addSource(kafkaConsumer);
        //TODO 4.对读取的数据进行类型转换
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);
//        jsonObjDS.print(">>>");
        //TODO 5.过滤出登录行为    uid!=null && (lastPageId=='login' ||lastPageId==null)
        SingleOutputStreamOperator<JSONObject> filterDS = jsonObjDS.filter(
                new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String uid = jsonObj.getJSONObject("common").getString("uid");
                        String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        return StringUtils.isNotEmpty(uid) && ("login".equals(lastPageId) || StringUtils.isEmpty(lastPageId));
                    }
                }
        );
//         filterDS.print(">>>");
        //TODO 6.指定Watermark以及提取事件时间字段
        SingleOutputStreamOperator<JSONObject> withWatermarkDS = filterDS.assignTimestampsAndWatermarks(
                WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<JSONObject>() {
                                    @Override
                                    public long extractTimestamp(JSONObject jsonObj, long recordTimestamp) {
                                        return jsonObj.getLong("ts");
                                    }
                                }
                        )
        );

        //TODO 7.按照uid进行分组
        KeyedStream<JSONObject, String> kededDS = withWatermarkDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("uid"));

        //TODO 8.使用Flink状态编程 判断独立用户以及当日活跃用户
        SingleOutputStreamOperator<UserActiveBean> processDS = kededDS.process(
                new KeyedProcessFunction<String, JSONObject, UserActiveBean>() {
                    private ValueState<String> lastLoginDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<String>("lastLoginDateState", String.class);
                        lastLoginDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public void processElement(JSONObject jsonObj, Context ctx, Collector<UserActiveBean> out) throws Exception {
                        Long ts = jsonObj.getLong("ts");
                        String curLoginDate = DateFormatUtil.toDate(ts);
                        Long uuCt = 0L;
                        Long activeCt = 0L;
                        String lastLoginDate = lastLoginDateState.value();

                        if (StringUtils.isNotEmpty(lastLoginDate)) {
                            //末次登陆日期不为空，进一步判断
                            if (!lastLoginDate.equals(curLoginDate)) {
                                //如果末次登陆日期不等于当天日期
                                activeCt = 1L;
                                uuCt = 1L;
                                lastLoginDateState.update(curLoginDate);
                            }
                        } else {
                            uuCt = 1L;
                            lastLoginDateState.update(curLoginDate);
                        }

                        if ( uuCt != 0L || activeCt != 0L) {
                            out.collect(new UserActiveBean("", "", activeCt, uuCt, ts));
                        }
                    }
                }
        );
        //TODO 9.开窗
        AllWindowedStream<UserActiveBean, TimeWindow> windowDS = processDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)));

        //TODO 10.聚合计算
        SingleOutputStreamOperator<UserActiveBean> reduceDS = windowDS.reduce(
                new ReduceFunction<UserActiveBean>() {
                    @Override
                    public UserActiveBean reduce(UserActiveBean value1, UserActiveBean value2) throws Exception {
                        value1.setActiveCt(value1.getActiveCt() + value2.getActiveCt());
                        value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                        return value1;
                    }
                },
                new AllWindowFunction<UserActiveBean, UserActiveBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<UserActiveBean> values, Collector<UserActiveBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());

                        for (UserActiveBean activeBean : values) {
                            activeBean.setStt(stt);
                            activeBean.setEdt(edt);
                            activeBean.setTs(System.currentTimeMillis());
                            out.collect(activeBean);
                        }

                    }
                }
        );
        //TODO 11.将聚合的结果写到CK
        reduceDS.print(">>>>");
        reduceDS.addSink(
                MyClickhouseUtil.getSinkFunction("insert into dws_user_active_login_window values(?,?,?,?,?)")
        );

        env.execute();
    }
}
